package com.event.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.event.exception.ArticleException;
import com.event.mapper.ArticleMapper;
import com.event.pojo.entity.Article;
import com.event.result.PageResult;
import com.event.service.ArticleService;
import com.event.utils.ThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author ihuwe
 * @description 针对表【article】的数据库操作Service实现
 * @createDate 2023-12-20 17:28:10
 */
@Service
@Slf4j
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article>
	implements ArticleService {
	
	@Override
	public PageResult<Article> getArticleList(Integer pageNum, Integer pageSize, Integer categoryId, String state) {
		Page<Article> page = new Page<>(pageNum, pageSize);
		LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper
			.eq(categoryId != null, Article::getCategoryId, categoryId)
			.eq(state != null, Article::getState, state)
			.eq(ThreadLocalUtil.get() != null, Article::getCreateUser, ThreadLocalUtil.get());
		IPage<Article> articlePage = this.page(page, queryWrapper);
		return new PageResult<>(page.getTotal(), articlePage.getRecords());
	}
	
	@Override
	public void updateArticle(Article article) {
		if (getOne(article) != null) {
			throw new RuntimeException(ArticleException.ARTICLE_TITLE_EXIST);
		}
		article.setUpdateTime(LocalDateTime.now());
		updateById(article);
	}

	private Article getOne(Article article) {
        return getOne(Wrappers.<Article>lambdaQuery().eq(ThreadLocalUtil.get() != null,
                Article::getCreateUser
                , ThreadLocalUtil.get()).eq(Article::getTitle, article.getTitle()));
	}

	@Override
	public void addArticle(Article article) {
		if (getOne(article) != null) {
			throw new RuntimeException(ArticleException.ARTICLE_TITLE_EXIST);
		}
		article.setCreateUser(ThreadLocalUtil.get());
		article.setCreateTime(LocalDateTime.now());
		article.setUpdateTime(LocalDateTime.now());
		save(article);
	}
}




